import { ElMessageBox } from 'element-plus'
import moment from "moment";
import message from './message'

// 消息弹框
export const ms = message

// 消息对话框
export const msb = ElMessageBox

/**
 * 对象数组深拷贝
 * @param {Array,Object} source 需要深拷贝的对象数组
 * @param {Array} noClone 不需要深拷贝的属性集合
 */
export function deepClone(source: any, noClone: string[] = []): any {
	if (!source && typeof source !== 'object') {
		throw new Error('error arguments deepClone')
	}
	const targetObj: any = source.constructor === Array ? [] : {}
	Object.keys(source).forEach((keys: string) => {
		if (source[keys] && typeof source[keys] === 'object' && noClone.indexOf(keys) === -1) {
			targetObj[keys] = deepClone(source[keys], noClone)
		} else {
			targetObj[keys] = source[keys]
		}
	})
	return targetObj
}

// 判断对象，数组，字符串是否为空，例如:  'undefined' , 'null' , '' , '   ' , {}  , [] 全部判断为空
export function isNull(obj: any): boolean {
	if (typeof obj === 'object') {
		let json = JSON.stringify(obj)
		if (json === '{}') {
			return true
		}
		if (json === '[]') {
			return true
		}
		return false
	}

	let str = String(obj)
	if (str === 'undefined' || str === 'null' || str === '' || !str || !/[^\s]/.test(str)) {
		return true
	}

	return false
}

// 控制台日志,支持传一个参数(对象/字符串), 也支持传两个参数(标志,日志消息<可以是对象,可以是字符串>)
export function clog(flag, value: any = 'xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx'): string {
	try {
		let tmp = ""
		// 如果value为默认值,则没有传递第二个参数,只处理第一个参数
		if (value === `xxxxxxxxxxxxxxxxxxx=Default-value_override+xxxxxxxxxxxxxxxxx`) {
			tmp = JSON.stringify(flag);
			console.log(tmp)
		} else if (isNull(value)) {
			tmp = JSON.stringify(flag);
			console.log(tmp + ":")
		} else if (isNull(flag)) {
			tmp = JSON.stringify(value);
			console.log(":" + tmp)
		} else {
			tmp = JSON.stringify(value);
			console.log(flag + ":" + tmp)
		}
		return tmp
	} catch (err) {
		console.log("log", err)
		return " 空对象或者空字符串 "
	}
}

// 日期格式化
export function dateFormatter(str, isDate = false) {
	if (isNull(str)) return undefined
	if (isDate === true) {
		return moment(str).format(
			'YYYY-MM-DD'
		)
	} else {
		return moment(str).format(
			'YYYY-MM-DD HH:mm:ss'
		)
	}
}

// 
export function dateFormatterNumber(str, hasTime = true, hasSecond = true): string {
	let d = new Date(str);
	if (isNull(str)) {
		let d = new Date();
	}
	let year = d.getFullYear();
	let month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
	let day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
	console.log(hasTime)
	if (hasTime) {
		let hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
		let minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
		let second = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
		console.log(year, month, day, year + "" + month + "" + day + "" + hour + "" + minute + "" + (hasSecond === true ? second : ""))
		return year + "" + month + "" + day + "" + hour + "" + minute + "" + (hasSecond === true ? second : "");
	} else {
		return year + "" + month + "" + day;
	}
}

export function enumFilter(source, item = [] as any, destination, myValue) {
	let aim = item.find(x => x[myValue === undefined ? "value" : myValue] === source)
	if (isNull(aim)) return source
	let describe = aim[destination === undefined ? "name" : destination]
	return describe
}

export function validate(ref) {
	let isValidate = true
	// await nextTick(function () {
	if (ref != null) {
		ref.validate((valid) => {
			if (!valid) {
				isValidate = false
			}
		})
	} else {
		isValidate = true
	}
	return isValidate;
}

// 节流
export function throttle(this: any, fn: Function, interval = 500) {
	let last = 0;
	return (...args) => {
		let now = +new Date();
		// 还没到时间
		if (now - last < interval) return;
		last = now;
		fn.apply(this, args);
	};
}

export function html2Escape(sHtml: string) {
	const dict = { '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' };
	return sHtml.replace(/[<>&"]/g, (c: string) => {
		return dict[c];
	});
}

let timestamp, timeout
export function debounce(func, wait, immediate) {
	let args, context, result
	const later = () => {
		// 距离上一次触发的时间间隔
		const last = (timestamp === undefined ? 0 : +new Date() - timestamp)
		// 上次被包装函数被调用时间间隔last小于设定时间间隔wait
		if (last < wait && last > 0) {
			//是否等待时间间隔达到后调用防抖 加上条件判断防止时间间隔内连续触发多个定时任务
			if (timeout == null) timeout = setTimeout(later, wait - last)
		} else {
			timeout = null
			// 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
			if (!immediate) {
				timestamp = +new Date()
				result = func.apply(context, args)
				if (!timeout) context = args = null
			}
		}
	}
	return later()
}
